package org.devocean.groupbuying.dao.impl;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.devocean.groupbuying.dao.UserDao;
import org.devocean.groupbuying.domain.User;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {

	@PersistenceContext
	private EntityManager em;

	public User findUser(String userName) {
		
			final List<User> lst = em
					.createQuery("SELECT us FROM User us" +
							" WHERE us.username =:userName",
							User.class).setParameter("userName", userName).getResultList();
			System.out.println(lst.size());
			final User user = lst.get(0);
			return user;
		
	}

	public List<User> findAllUsers() {
		return em.createQuery("select u from User u", User.class)
				.getResultList();
	}

	public long countUser() {
		return em.createQuery("select count(u) from User u", long.class)
				.getSingleResult();
	}

	public User findUserById(Integer id) {
		return em.find(User.class, id);
	}

	public void deleteUser(int id) {
		User user = em.find(User.class, id);
		if (user != null) {
			em.remove(user);
		}

	}

	public User saveUser(User user) {
		em.persist(user);
		return user;
	}

	public User updateUser(User user) {
		em.merge(user);
		return user;
	}
}
